package com.wl156.activities.find;

import java.util.List;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
import com.wl156.lite.R;

public class PlaceMap extends MapActivity implements OnClickListener {

	private static final String TAG = null;

	private MapView mMapView;
	String longtitude;
	String latitude;
	String name;
	private Button mRefresh;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.act_place_map);

		mMapView = (MapView) findViewById(R.id.mapview);
		mRefresh = (Button) findViewById(R.id.refresh);
		mRefresh.setOnClickListener(this);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			longtitude = extras.getString("longitude");
			latitude = extras.getString("latitude");
			name = extras.getString("name");
			Drawable marker = getResources().getDrawable(R.drawable.map_marker);
			marker.setBounds(0, 0, marker.getIntrinsicWidth(),
					marker.getIntrinsicHeight());
			PlaceOverlay overlay = new PlaceOverlay(marker, name);
			mMapView.getOverlays().clear();
			mMapView.getOverlays().add(overlay);

			GeoPoint pt = overlay.getCenter(); // get the first-ranked point
			mMapView.getController().setCenter(pt);
			// 设置地图的缩放级别。这个值的取值范围是[1,21],
			mMapView.getController().setZoom(15);
		} else {
			try {
				name = "我的位置";
				locationManager = (LocationManager) this
						.getSystemService(Context.LOCATION_SERVICE);

				// mConfirm.setText("定位中，请稍候");

				List<String> providers = locationManager.getProviders(true);

				// String providers =
				// Settings.Secure.getString(getContentResolver(),
				// Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
				// // 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
				// // java.lang.IllegalArgumentException: provider=network,gps
				// String[] items = providers.split(",");
				for (String item : providers) {
					Location loc = locationManager.getLastKnownLocation(item);
					if (loc != null) {
						myLatitude = String.valueOf(loc.getLatitude());
						myLongitude = String.valueOf(loc.getLongitude());
					}
					// updateCurrentLocationView(myLatitude, myLongitude);
					longtitude = myLongitude;
					latitude = myLatitude;

					Drawable marker = getResources().getDrawable(
							R.drawable.map_marker);
					marker.setBounds(0, 0, marker.getIntrinsicWidth(),
							marker.getIntrinsicHeight());
					PlaceOverlay overlay = new PlaceOverlay(marker, name);
					mMapView.getOverlays().clear();
					mMapView.getOverlays().add(overlay);

					GeoPoint pt = overlay.getCenter(); // get the first-ranked
														// point
					mMapView.getController().setCenter(pt);
					// 设置地图的缩放级别。这个值的取值范围是[1,21],
					mMapView.getController().setZoom(15);
				}

				openGPSSettings();
			} catch (Exception e) {
			}
		}

	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	class PlaceOverlay extends ItemizedOverlay<OverlayItem> {
		GeoPoint gp;
		Drawable defaultMarker;
		String name;

		public PlaceOverlay(Drawable defaultMarker, String name) {
			super(defaultMarker);
			this.defaultMarker = defaultMarker;
			this.name = name;

			Log.d(TAG, "latitude: " + latitude + ", longtitude: " + longtitude);
			gp = new GeoPoint((int) (Double.valueOf(latitude) * 1E6),
					(int) (Double.valueOf(longtitude) * 1E6));
			populate();
		}

		@Override
		public void draw(Canvas canvas, MapView mapView, boolean shadow) {

			try {
				Projection projection = mapView.getProjection();
				OverlayItem overLayItem = getItem(0); // 得到给定索引的item
				String title = overLayItem.getTitle();
				// 把经纬度变换到相对于MapView左上角的屏幕像素坐标
				Point point = projection.toPixels(overLayItem.getPoint(), null);
				// Paint paintCircle = new Paint();
				// paintCircle.setColor(Color.RED);
				// canvas.drawCircle(point.x, point.y, 5, paintCircle); // 画圆
				Paint paintText = new Paint();
				paintText.setColor(Color.RED);
				paintText.setAntiAlias(true);
				paintText.setFakeBoldText(true);
				paintText.setTextSize(20);
				canvas.drawText(title, point.x - paintText.measureText(title)
						/ 2, point.y - defaultMarker.getIntrinsicHeight() - 5,
						paintText); // 绘制文本

				super.draw(canvas, mapView, shadow);
				boundCenterBottom(defaultMarker);
			} catch (Exception e) {
			}
		}

		@Override
		protected OverlayItem createItem(int i) {
			return new OverlayItem(gp, name, "snippet");
		}

		@Override
		public int size() {
			return 1;
		}
	}

	private String myLongitude = "";
	private String myLatitude = "";
	private static final int GPS_FAILED = 0;
	private static final int NETWORK_FAILED = 1;
	LocationListener locationListener = new MyLocationListener();
	LocationListener locationListener1 = new MyLocationListener();

	class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location location) {
			Log.d(TAG, "location.longitude: " + location.getLongitude()
					+ ", latitude: " + location.getLatitude());
			myLongitude = String.valueOf(location.getLongitude());
			myLatitude = String.valueOf(location.getLatitude());

			longtitude = myLongitude;
			latitude = myLatitude;

			Drawable marker = getResources().getDrawable(R.drawable.map_marker);
			marker.setBounds(0, 0, marker.getIntrinsicWidth(),
					marker.getIntrinsicHeight());
			PlaceOverlay overlay = new PlaceOverlay(marker, name);
			mMapView.getOverlays().clear();
			mMapView.getOverlays().add(overlay);

			GeoPoint pt = overlay.getCenter(); // get the first-ranked
												// point
			mMapView.getController().setCenter(pt);
			// 设置地图的缩放级别。这个值的取值范围是[1,21],
			mMapView.getController().setZoom(15);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			Log.d(TAG, "onStatusChanged: provider: " + provider + ", status: "
					+ status);
		}

		public void onProviderEnabled(String provider) {
			Log.d(TAG, "onProviderEnabled");
		}

		public void onProviderDisabled(String provider) {
			Log.d(TAG, "onProviderDisabled");
		}
	};

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			// case GPS_FAILED:
			// if (TextUtils.isEmpty(myLongitude)) {
			// locationManager.removeUpdates(locationListener);
			// startFetchingLocation(LocationManager.NETWORK_PROVIDER);
			// }
			// break;
			case NETWORK_FAILED:
			default:
				if (TextUtils.isEmpty(myLongitude)) {
					locationManager.removeUpdates(locationListener);
					// Toast.makeText(FindPlace.this, "定位失败", Toast.LENGTH_LONG)
					// .show();
					AlertDialog.Builder builer = new AlertDialog.Builder(
							PlaceMap.this);
					builer.setMessage("定位失败，请您确保你已经连接网络或者已经开启GPS");
					builer.setNegativeButton("知道了", null);
					builer.show();
				}
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d(TAG, "requsetCode: " + requestCode + ", resultCode: "
				+ resultCode);
		String provider = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		if (provider != null) {
			Log.v(TAG, " Location providers: " + provider);
			// 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
			// java.lang.IllegalArgumentException: provider=network,gps

			if (provider.contains("gps")) {
				startFetchingLocation(LocationManager.GPS_PROVIDER);
			} else if (provider.contains("network")) {
				startFetchingLocation(LocationManager.NETWORK_PROVIDER);
			}
		} else {
			Toast.makeText(this, "无法获取到您的位置，请开启GPS或者网络", Toast.LENGTH_SHORT)
					.show();
		}
	}

	LocationManager locationManager;

	private void startFetchingLocation(String provider) {
		// LocationManager.GPS_PROVIDER
		// LocationManager.NETWORK_PROVIDER;
		String providers = Settings.Secure.getString(getContentResolver(),
				Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		// 03-10 22:39:58.207: E/AndroidRuntime(20101): Caused by:
		// java.lang.IllegalArgumentException: provider=network,gps
		String[] items = providers.split(",");
		try {
			for (String item : items) {
				locationManager.requestLocationUpdates(item, 0, 0,
						new MyLocationListener());
				mHandler.sendMessageDelayed(
						Message.obtain(mHandler, NETWORK_FAILED), 5000);
			}
		} catch (Exception e) {
		}

		// locationManager
		// .requestLocationUpdates(provider, 0, 0, locationListener);
		// if (provider.equals(LocationManager.GPS_PROVIDER)) {
		// mHandler.sendMessageDelayed(Message.obtain(mHandler, GPS_FAILED),
		// 4000);
		// } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) {
		// mHandler.sendMessageDelayed(
		// Message.obtain(mHandler, NETWORK_FAILED), 2000);
		// }
	}

	private void openGPSSettings() {
		LocationManager alm = (LocationManager) this
				.getSystemService(Context.LOCATION_SERVICE);
		if (alm.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
			Toast.makeText(this, "GPS已经开启", Toast.LENGTH_SHORT).show();

			startFetchingLocation(LocationManager.GPS_PROVIDER);
		} else {
			AlertDialog.Builder builer = new Builder(this);
			builer.setMessage("GPS尚未开启，前去开启？");
			builer.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent myIntent = new Intent(
									Settings.ACTION_LOCATION_SOURCE_SETTINGS);
							startActivityForResult(myIntent, 0);
						}
					});
			builer.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							startFetchingLocation(LocationManager.NETWORK_PROVIDER);
						}
					});
			builer.show();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.refresh:
			mMapView.invalidate();
			break;
		default:
			break;
		}
	}
}
